package monpkg.view;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RMISecurityManager;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import monpkg.rmi.IAnnuaireImpl;

/**
 * @author Yannick Bouchot
 * @author Jonathan Romero
 */

@SuppressWarnings("unused")
public class annuaireRMI extends HttpServlet {
	IAnnuaireImpl annuaire = null;

	/**
	 * methode permettant de recuperer l'annuaire du serveur
	 */
	@SuppressWarnings("deprecation")
	protected IAnnuaireImpl getAnnuaireServer() {
		// Set the security manager if it hasn't been done already.
		// Provides protection from a malicious DaytimeServer stub.
		// if (System.getSecurityManager() == null) {
		// System.setSecurityManager(new RMISecurityManager());
		// }

		try {
			Registry registry = LocateRegistry.getRegistry(getRegistryHost(),
					getRegistryPort());
			return (IAnnuaireImpl) registry.lookup(getRegistryName());
		} catch (Exception e) {
			getServletContext().log(e, "Problem getting annuaireDAO reference");
			return null;
		}
	}

	/**
	 * methode permettant de recuperer le nom du registre
	 */
	private String getRegistryName() {
		String name = getInitParameter("annuaireDAO");
		return (name == null ? "annuaireDAO" : name);
	}

	/**
	 * methode permettant de recuperer le nom de l'hote du registre
	 */
	private String getRegistryHost() {
		// Return either the hostname given by "registryHost" or
		// if no name was given return null to imply localhost
		return getInitParameter("localhost");
	}

	/**
	 * methode permettant de recuperer le port du registre
	 */
	private int getRegistryPort() {
		try {
			return Integer.parseInt(getInitParameter("annuaireDAO"));
		} catch (NumberFormatException e) {
			return Registry.REGISTRY_PORT;
		}
	}

	/**
	 * methode repondant aux requetes htlm de type GET
	 */
	public void doGet(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {

		res.setContentType("text/plain");
		PrintWriter out = res.getWriter();

		// Get and print the current time on the (possibly remote) daytime host
		out.println("coucou");
	}
}
